<template>
  <!-- 财务审核 -->
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="退款状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="退款状态"
          clearable
          size="small"
          style="width: 110px"
        >
          <el-option
            v-for="dict in statusList"
            :key="dict.code"
            :label="dict.msg"
            :value="dict.code"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="退款类型" prop="orderType">
        <el-select
          v-model="queryParams.orderType"
          placeholder="退款类型"
          clearable
          size="small"
          style="width: 110px"
        >
          <el-option
            v-for="dict in orderTypeList"
            :key="dict.code"
            :label="dict.msg"
            :value="dict.code"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="申请日期" prop="startDate">
        <el-date-picker
          v-model="payDate"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="getPreDateArr"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="订单号" prop="keyword">
        <el-autocomplete
          style="width: 280px"
          class="inline-input"
          clearable
          v-model="keyword"
          :fetch-suggestions="querySearch"
          placeholder="请输入订单号、手机号、班次搜索"
          @select="handleSelect"
          @keyup.enter.native="handleQuery"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          v-hasPermi="['finance:RefundInfoes:query']"
          @click="handleQuery"
          >查询</el-button
        >
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 15px">
      <el-button
        type="primary"
        size="mini"
        v-hasPermi="['finance:RefundInfoes:edit']"
        @click="agreeArr"
        >批量同意</el-button
      >
      <el-button
        type="primary"
        size="mini"
        v-hasPermi="['finance:RefundInfoes:edit']"
        @click="isRefuse"
        >批量拒绝</el-button
      >
    </div>
    <el-table
      v-loading="loading"
      :data="list"
      :max-height="tableHeight"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        :selectable="checkItem"
        width="55"
        align="center"
      />
      <el-table-column label="序号" align="center" type="index" width="50" />
      <el-table-column label="订单编号" align="center" prop="sn" width="150" />
      <el-table-column label="分销商" align="center" prop="traderaccount" />
      <el-table-column label="退款状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ getStatus(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实付金额" align="center" prop="totalpay">
        <template slot-scope="scope">
          <span>{{ scope.row.ticketprice * scope.row.ticketamount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款金额" align="center" prop="refundfee" />
      <el-table-column
        label="退款原因"
        align="center"
        prop="refundcontent"
        width="400"
      />
      <el-table-column label="申请人" align="center" prop="realname" />
      <el-table-column
        label="申请时间"
        align="center"
        prop="operatetime"
        width="170"
      >
        <template slot-scope="scope">
          <span>{{ newDate(scope.row.operatetime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="toMessage(scope.row.sn)"
            v-hasPermi="['finance:RefundInfoes:query']"
            >详情</el-button
          >
          <el-button
            v-if="scope.row.status == 0"
            type="text"
            size="mini"
            @click="agree(scope.row)"
            v-hasPermi="['finance:RefundInfoes:edit']"
            >同意</el-button
          >
          <el-button
            v-if="scope.row.status == 0"
            type="text"
            size="mini"
            @click="refuseBtn(scope.row)"
            v-hasPermi="['finance:RefundInfoes:edit']"
            >拒绝</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span>请输入拒绝原因：</span>
      <div style="margin-top: 20px">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入拒绝原因"
          v-model="textarea"
        >
        </el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="refuse">确 定</el-button>
      </span>
    </el-dialog>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  auditList,
  edit,
  oneEdit,
  batchConsentorrejection,
} from "@/api/finance/audit";
import utils from "../../js/index";

export default {
  name: "Audit",
  components: {},
  data() {
    return {
      dialogVisible: false,
      textarea: "",
      keyword: "",
      payDate: "",
      statusList: [
        { msg: "全部", code: "" },
        { msg: "待处理", code: 0 },
        { msg: "同意退款", code: 1 },
        { msg: "拒绝退款", code: 2 },
      ],
      // orderTypeList: [{ msg: "申请退款", code: "申请退款" }],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: 0,
        beginTime: "",
        endTime: "",
        keyword: "",
        orderType: "申请退款",
      },
      arr: [],
    };
  },
  created() {
    this.tableHeight = window.innerHeight - 300;
    this.getSearchList();
    this.getList();
  },
  methods: {
    checkItem(row) {
      return row.status == 0;
    },
    toMessage(code) {
      // 跳转到详情页面
      this.$router.push({
        path: `orderMessage`,
        query: {
          orderCode: code,
        },
      });
    },

    getPreDateArr(date) {
      this.queryParams.beginTime = date[0];
      this.queryParams.endTime = date[1];
    },
    getStatus(val) {
      switch (val) {
        case 0:
          return "待处理";
          break;
        case 1:
          return "同意退款";
          break;
        case 2:
          return "拒绝退款";
          break;

        default:
          break;
      }
    },
    handleSelect(item) {
      console.log(item);
    },
    // 订单号历史记录
    getSearchList() {
      try {
        if (localStorage.getItem("searchList")) {
          this.arr = JSON.parse(localStorage.getItem("searchList"));
        }
      } catch (err) {}
      this.arr.unshift({
        value: this.keyword,
        address: this.keyword,
      });
      this.arr = utils.utils.arrUnique(this.arr);
      this.arr.splice(10, this.arr.length - 9);
      localStorage.setItem("searchList", JSON.stringify(this.arr));
    },
    querySearch(queryString, cb) {
      try {
        var restaurants = this.arr;
        var results = queryString
          ? restaurants.filter(this.createFilter(queryString))
          : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      } catch (err) {}
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      this.queryParams.memberphonenumber =
        this.keyword.length == 11 ? this.keyword : "";
      this.queryParams.sn = this.keyword.length > 11 ? this.keyword : "";
      auditList(this.addDateRange(this.queryParams, this.payDate))
        .then((response) => {
          if (response.code == 200) {
            this.list = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    newDate(date) {
      return utils.utils.NewDate(date);
    },

    refuseBtn(data) {
      if (data && data.status == 0) {
        this.ids = [data];
        this.dialogVisible = true;
      } else {
        this.ids = [];
        this.$message.error("只有待处理状态下才可操作！");
        return;
      }
    },
    isRefuse() {
      if (this.ids.length == 0) {
        this.$message.error("请选择批量退款订单");
        return;
      }
      this.dialogVisible = true;
    },
    refuse() {
      if (this.textarea.length == 0) {
        this.$message.error("请输入退款原因");
        return;
      }
      var arr = [];
      this.ids.map((item) => {
        arr.push({ id: item.id, status: 2, refundcontent: this.textarea });
      });
      if (arr.length == 1) {
        oneEdit(...arr)
          .then((res) => {
            if (res.code == 200) {
              this.dialogVisible = false;
              this.getList();
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        edit(JSON.stringify(arr))
          .then((res) => {
            if (res.code == 200) {
              this.dialogVisible = false;
              this.getList();
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    agreeArr() {
      var arr = [];
      this.ids.map((item) => {
        arr.push({
          id: item.id,
          status: 1,
          refundcontent: this.textarea,
        });
      });
      this.$confirm("此操作将同意退款, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        edit(JSON.stringify(arr)).then((res) => {
          if (res.code == 200) {
            this.dialogVisible = false;
            this.getList();
            this.$message.success(res.msg);
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    agree(data) {
      this.$confirm("此操作将同意退款, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          oneEdit({ id: data.id, status: 1 })
            .then((res) => {
              if (res.code == 200) {
                this.$message.success(res.msg);
                this.getList();
              } else {
                this.$message.error(res.msg);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {});
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
      this.getSearchList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection;
      selection.map((item) => {
        if (item.status != 0) {
          this.$message.error("只有待处理状态下才可操作！");
          this.ids = [];
        }
      });
      this.multiple = !selection.length;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const infoIds = row.infoId || this.ids;
      this.$confirm(
        '是否确认删除访问编号为"' + infoIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delLogininfor(infoIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      downloadorder(this.queryParams);
    },
  },
};
</script>

<style scoped>
.refItem {
  line-height: 50px;
}
#refDiv {
  font-size: 15px;
}
</style>